﻿using CoreShop.App.Units.Interface;
using CoreShop.Library;
using CoreShop.Model;
using CoreShop.Services;
using Loading;
using Model.ProductModel;
using MySqlX.XDevAPI.Common;
using SqlSugar;
using SqlSugar.Extensions;
using Sunny.UI;
using Sunny.UI.Win32;
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Threading;

namespace CoreShop.App
{
    public partial class frmDiscounts : UIForm
    {
        private int type = (int)GlobalEnumVars.DiscountMode.Discount;//0整单打折,1打折，2减免，3改价
        public corecmsfoodordering orderingSelected = null;
        private corecmsfood foodInfo = null;
        private corecmsfoodspec foodspec = null;
        public DicountInfo dicountInfo = null;
        OpaqueCommand cmd = new OpaqueCommand();
        public frmDiscounts(corecmsfoodordering _orderingSelected, int _type)
        {
            this.type = _type;
            this.orderingSelected = _orderingSelected;
            InitializeComponent();
            numKeybord.FillColor = System.Drawing.Color.White;
            loadData();
            txtValue.TextBox.GotFocus += txtValue_GotFocus;
            txtValue.Focus();
        }

        private void txtValue_GotFocus(object sender, System.EventArgs e)
        {
            numKeybord.SetTextBox((UIEdit)sender, UITextBox.UIEditType.Double, 4);
        }

        private void loadData()
        {
            if (orderingSelected != null)
            {
                foodInfo = new corecmsfoodServices().GetById(orderingSelected.foodId);
                foodspec = new corecmsfoodspecServices().GetById(orderingSelected.foodSpecId);
            }
            btnDiscount1.Tag = AppConstVars.systemsetup.discount1.ObjToInt(0);
            btnDiscount1.Text = AppConstVars.systemsetup.discount1.ObjToString("0") + "折";
            btnDiscount2.Tag = AppConstVars.systemsetup.discount2.ObjToInt(0);
            btnDiscount2.Text = AppConstVars.systemsetup.discount2.ObjToString("0") + "折";
            btnDiscount3.Tag = AppConstVars.systemsetup.discount3.ObjToInt(0);
            btnDiscount3.Text = AppConstVars.systemsetup.discount3.ObjToString("0") + "折";
            btnDiscount4.Tag = AppConstVars.systemsetup.discount4.ObjToInt(0);
            btnDiscount4.Text = AppConstVars.systemsetup.discount4.ObjToString("0") + "折";
            mbtDiscountTag.Clear();
            mbtDiscountTag.AutoWidth = true;
            var tagList = new corecmsfoodtagServices().QueryAsync((int)GlobalEnumVars.FoodTag.PriceTag);
            foreach (var item in tagList)
            {
                mbtDiscountTag.Add(item.content, item.id);
            }

            mbtDiscountType.Clear();
            mbtDiscountType.AutoWidth = false;
            mbtDiscountType.ItemSize = new System.Drawing.Size(115, 50);
            mbtDiscountType.FontSize = 13;
            mbtDiscountType.MaxSelected = 1;
            if (type == (int)GlobalEnumVars.DiscountMode.ChangPrice)
            {
                this.btnEditPrice.Visible = true;
                this.btnEditPriceDay.Visible = true;
                this.pnlTitle.Text = "商品改价";
                if ((foodInfo != null) && (foodspec.chgPrice))
                {
                    lblPrice.Text = orderingSelected.price.ToString("#0.00");
                    mbtDiscountType.Add("改价", (int)GlobalEnumVars.DiscountMode.ChangPrice, true);
                    SetControlState((int)GlobalEnumVars.DiscountMode.ChangPrice);
                    mbtDiscountType.Visible = false;
                }
            }
            else {
                this.pnlTitle.Text = "商品打折";
                bool selectBtn = true;
                if ((foodInfo != null) && (foodspec.disItem))
                {
                    selectBtn = false;
                    mbtDiscountType.Add("单品打折", (int)GlobalEnumVars.DiscountMode.Discount, true);
                    mbtDiscountType.Add("单品减免", (int)GlobalEnumVars.DiscountMode.ReduceAmount, false);                    
                }
                if (AppConstVars.systemsetup.isDiscountAll)
                {
                    mbtDiscountType.Add("整单打折", (int)GlobalEnumVars.DiscountMode.DiscountAll, selectBtn);
                    if (selectBtn)
                        type = (int)GlobalEnumVars.DiscountMode.DiscountAll;//单品不能打折，转为整个单打折
                }                
                if ((foodInfo != null) && (foodspec.disItem))
                    SetControlState((int)GlobalEnumVars.DiscountMode.Discount);
                else
                if (AppConstVars.systemsetup.isDiscountAll)
                   SetControlState((int)GlobalEnumVars.DiscountMode.DiscountAll);
            }
        }

        private void btnDiscount48_Click(object sender, System.EventArgs e)
        {
            int tag = ((UIButton)sender).Tag.ToString().ToInt();
            txtValue.Text = tag.ToString();
            txtValue.Focus();
            txtValue.SelectAll();
        }

        private void btnExit_Click(object sender, System.EventArgs e)
        {
          
        }

        public string desc = "";
        private void mbtDiscountTag_SelectedChanged(object sender, System.EventArgs e)
        {
            UIMultiButtons button = (UIMultiButtons)sender;
            UIButton btn = button.SelectedBtn;

            if (btn != null)
            {
                string btnTxt = btn.Text;
                bool btnSelect = btn.Selected;
                if (btnSelect)
                    desc = btnTxt;
                else
                    desc = "";
            }            
        }

        private void SetControlState(int mType)
        {
            lblTag.Text = "";
            //btnYes.Text = EnumHelper.GetDescByValue<GlobalEnumVars.DiscountMode>(type);
            btnDiscount1.Visible = false;
            btnDiscount2.Visible = false;
            btnDiscount3.Visible = false;
            btnDiscount4.Visible = false;
            txtValue.ReadOnly = false;
            numKeybord.Visible = true;
            txtValue.Focus();
            txtValue.SelectAll();
            switch (mType)
            {
                case (int)GlobalEnumVars.DiscountMode.DiscountAll:
                case (int)GlobalEnumVars.DiscountMode.Discount:
                    btnDiscount1.Visible = true;
                    btnDiscount2.Visible = true;
                    btnDiscount3.Visible = true;
                    btnDiscount4.Visible = true;
                    lblTag.Text = "%";
                    txtValue.Watermark = "打8折请输入80";
                    if ((mType == (int)GlobalEnumVars.DiscountMode.DiscountAll) && (!AppConstVars.systemsetup.isDiscountAll)
                        || (!foodInfo.isDiscount.ObjToBool()) && (mType == (int)GlobalEnumVars.DiscountMode.Discount))
                    {
                        txtValue.Clear();
                        txtValue.ReadOnly = true;//不允许整单打折或单品打折
                    }
                    break;
                case (int)GlobalEnumVars.DiscountMode.ReduceAmount:
                    txtValue.Watermark = "请输入减免金额";
                    break;
                case (int)GlobalEnumVars.DiscountMode.ChangPrice:
                    txtValue.Watermark = "请输入商品售价";
                    break;
            }
        }

        private void mbtDiscountType_SelectedChanged(object sender, EventArgs e)
        {
            UIMultiButtons button = (UIMultiButtons)sender;
            UIButton btn = button.SelectedBtn;
            if (btn != null) type = CommFunc.ConvertToInt32(btn.Tag);
            SetControlState(type);
        }

        /// <summary>
        /// 校验数值
        /// </summary>
        /// <returns></returns>
        private bool checkValues()
        {
            decimal inputValue = txtValue.Text.ObjToDecimal(0);
            #region 检测权限
            if (type == (int)GlobalEnumVars.DiscountMode.DiscountAll)
            {
                if (!ProcessUtil.GetUserRole(GlobalEnumVars.UserRoleType.isOrderDiscount, 0)) return false;
                if (!ProcessUtil.GetUserRole(GlobalEnumVars.UserRoleType.maxDiscountValue, txtValue.Text.ToInt())) return false;
            }
            else
            {
                if (type == (int)GlobalEnumVars.DiscountMode.Discount)
                {
                    if (!ProcessUtil.GetUserRole(GlobalEnumVars.UserRoleType.isProductDiscount, inputValue)) return false;
                    if (!ProcessUtil.GetUserRole(GlobalEnumVars.UserRoleType.maxDiscountValue, txtValue.Text.ToInt())) return false;
                }
                else if (type == (int)GlobalEnumVars.DiscountMode.ReduceAmount)
                {
                    var specModel = new corecmsfoodspecServices().GetById(orderingSelected.foodSpecId);
                    if ((specModel != null) && (!specModel.disItem))
                    {
                        UIMessageBox.Show("该商品不充许打折，无法减免操作。");
                        return false;
                    }
                    if ((specModel != null) && (!specModel.chgPrice))
                    {
                        UIMessageBox.Show("该商品不充许改价，无法减免操作。");
                        return false;
                    }
                    if (!ProcessUtil.GetUserRole(GlobalEnumVars.UserRoleType.maxReduceAmount, txtValue.Text.ObjToDecimal(0))) return false;
                }
                else if (type == (int)GlobalEnumVars.DiscountMode.ChangPrice)
                {
                    decimal mValue = orderingSelected.price - txtValue.Text.ObjToDecimal(0);
                    if (!ProcessUtil.GetUserRole(GlobalEnumVars.UserRoleType.isProductDiscount, mValue)) return false;
                    if (!ProcessUtil.GetUserRole(GlobalEnumVars.UserRoleType.maxReduceAmount, mValue)) return false;
                }
            }
            #endregion
            #region 检测单价控制
            decimal sNewPrice = 0;
            if (type == (int)GlobalEnumVars.DiscountMode.Discount)
            {
                sNewPrice = CommFunc.ConvertToDecimal(txtValue.Text)/ 100 * orderingSelected.price;
            }
            else if (type == (int)GlobalEnumVars.DiscountMode.ReduceAmount)
            {
                if (orderingSelected.price == 0)
                {
                    UIMessageTip.ShowWarning(btnDiscount2, "原价为0，无法减免", 3000);
                    return false;
                }
                sNewPrice = orderingSelected.price - CommFunc.ConvertToDecimal(txtValue.Text);                
            }
            else if (type == (int)GlobalEnumVars.DiscountMode.ChangPrice)
            {
                if (orderingSelected.price == 0) return true;
                sNewPrice = CommFunc.ConvertToDecimal(txtValue.Text);
            }
            if (sNewPrice < orderingSelected.minPrice)
            {
                string msg = "商品【" + lbl_caption.Text + "】的最低售价为【"
                    + (orderingSelected.minPrice).ToString("0.0#") + "】，不能低于限定值。";
                UIMessageBox.Show(msg, "提示：", UIStyle.Green, UIMessageBoxButtons.OK);
                return false;
            }
            if ((sNewPrice > orderingSelected.maxPrice) && (orderingSelected.maxPrice > 0))
            {
                string msg = "商品【" + lbl_caption.Text + "】的最高售价为【"
                    + (orderingSelected.maxPrice).ToString("0.0#") + "】，不能高于限定值。";
                UIMessageBox.Show(msg, "提示：", UIStyle.Green, UIMessageBoxButtons.OK);
                return false;
            }
            #endregion
            return true;
        }

        private void numKeybord_OKButtonClick(object sender, string text, int intvalue, double doublevalue)
        {
            SetOkAndClose();
            //DoValueChanged(sender, info);
        }

        private void SetOkAndClose()
        {
            if (txtValue.Text.IsNullOrEmpty())
            {
                UIMessageTip.ShowWarning(txtValue, "请输入正确的值");
                return;
            }
            if (!checkValues()) return;
                
            dicountInfo = new DicountInfo(type, txtValue.Text.ObjToDecimal(0), desc);
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void txtValue_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {            
            if (e.KeyChar == 12290)
            {
                string str = txtValue.Text;
                int idx = txtValue.SelectionStart;
                str = str.Insert(idx, ".");
                txtValue.Text = str;
                txtValue.SelectionStart = idx + 1;
                txtValue.Focus();
                e.Handled = true;
            } 
            else
            if (e.KeyChar == (char)13) SetOkAndClose();
        }

        private void btnEditPrice_Click(object sender, EventArgs e)
        {
            if (txtValue.Text.IsNullOrEmpty())
            {
                UIMessageTip.ShowWarning(txtValue, "请输入正确的值");
                return;
            }
            try
            {
                cmd.ShowOpaqueLayer(pnl_Form, 125, true);
                if (!ProcessUtil.GetUserRoleAny(GlobalEnumVars.UserRoleType.isEditGoodsPrice, 0, true)) return;
                var foodInfo = new corecmsfoodServices().GetById(orderingSelected.foodId);
                var specInfo = new corecmsfoodspecServices().GetById(orderingSelected.foodSpecId);
                if (foodInfo == null || specInfo == null)
                {
                    UIMessageTip.ShowWarning(btnEditPrice, "没有找到相关的商品信息.");
                    return;
                }
                if (foodInfo.parentTenantId == foodInfo.corpId)
                {
                    UpdateSpuPrice(foodInfo, specInfo);//本店商品。直接修改价格
                }
                else
                {
                    UpdateBranchPrice(foodInfo, specInfo);//本店商品。修改价格表
                }
            }
            catch (Exception ex)
            {
                UIMessageBox.Show("获取卡类型失败:。" + ex.Message);
            }
            finally { cmd.HideOpaqueLayer(); }
        }


        /// <summary>
        /// 修改商品价格
        /// </summary>
        /// <param name="foodInfo"></param>
        /// <param name="specInfo"></param>
        private async void UpdateSpuPrice(corecmsfood foodInfo, corecmsfoodspec specInfo)
        {
            SpuSpecUpdateDto updateDto = new SpuSpecUpdateDto();
            updateDto.pdtSpuSpecId = orderingSelected.foodSpecId;
            updateDto.spuId = orderingSelected.foodId;
            updateDto.saPrice = CommFunc.ConvertToDecimal(txtValue.Text);
            updateDto.canDefault = 1;
            if (foodInfo.foodSpecId == specInfo.id) updateDto.canDefault = 0;
            var bl = await FoodApiUtil.UpdateSpuPrice(updateDto, AppConstVars.sysUser);
            if (bl.status)
            {
                new corecmsfoodspecServices().Change<corecmsfoodspec>().Update(a => new corecmsfoodspec()
                {
                    posPrice = updateDto.saPrice,
                }, a => a.id == updateDto.pdtSpuSpecId);
                await FoodApiUtil.LoadGoodDataAsync(orderingSelected.foodId);
                SetOkAndClose();
            }
            else
            {
                UIMessageTip.ShowWarning(btnEditPrice, bl.msg);
            }
        }

        /// <summary>
        /// 总部商品的价格修改->修改价格表
        /// </summary>
        /// <param name="foodInfo"></param>
        /// <param name="specInfo"></param>
        private async void UpdateBranchPrice(corecmsfood foodInfo, corecmsfoodspec specInfo)
        {
            BranchPriceDto updateDto = new BranchPriceDto();       
            updateDto.tenantId = AppConstVars.sysStore.corpId;
            updateDto.branchId = AppConstVars.sysStore.branchId;
            updateDto.spuId = specInfo.foodId;
            updateDto.pdtSpuSpecId = specInfo.id;            
            updateDto.saPrice = CommFunc.ConvertToDecimal(txtValue.Text);            
            var bl = await FoodApiUtil.UpdateBranchPrice(updateDto, AppConstVars.sysUser);
            if (bl.status)
            {
                new corecmsfoodspecServices().Change<corecmsfoodspec>().Update(a => new corecmsfoodspec()
                {
                    posPrice = updateDto.saPrice,
                }, a => a.id == specInfo.id);
                new corecmsfoodpriceServices().Change<corecmsfoodprice>().Update(a => new corecmsfoodprice()
                {
                    saPrice = updateDto.saPrice,
                }, a => a.pdtSpuSpecId == specInfo.id);
                await FoodApiUtil.LoadGoodDataAsync(specInfo.foodId);
                SetOkAndClose();
            }
            else
            {
                UIMessageTip.ShowWarning(btnEditPrice, bl.msg);
            }
        }

        private async void btnEditPriceDay_Click(object sender, EventArgs e)
        {
            if (!ProcessUtil.GetUserRoleAny(GlobalEnumVars.UserRoleType.isChgPrice, 0, true)) return;
            var specInfo = new corecmsfoodspecServices().GetById(orderingSelected.foodSpecId);
            if (specInfo == null)
            {
                UIMessageTip.ShowWarning(btnEditPrice, "没有找到相关的商品信息.");
                return;
            }
            try
            {
                cmd.ShowOpaqueLayer(pnl_Form, 125, true);
                GsPdtChgPriceModel gsPdtChgPriceModel = new GsPdtChgPriceModel();
                gsPdtChgPriceModel.branchId = AppConstVars.sysStore.branchId.ToString();
                gsPdtChgPriceModel.lines = new List<PdtChgPriceInfo>();
                PdtChgPriceInfo pdtChgprice = new PdtChgPriceInfo();
                pdtChgprice.spuId = specInfo.foodId.ToString();
                pdtChgprice.pdtSpuSpecId = specInfo.id.ToString();
                pdtChgprice.nowSalePrice = CommFunc.ConvertToDecimal(txtValue.Text);
                pdtChgprice.nowVipPrice = specInfo.vipPrice;
                pdtChgprice.nowVvipPrice = specInfo.vvipPrice;
                pdtChgprice.nowCommPrice = specInfo.commPrice;
                gsPdtChgPriceModel.lines.Add(pdtChgprice);
                   
                var bl = await FoodApiUtil.ChgPriceHeadByPos(gsPdtChgPriceModel, AppConstVars.sysUser);
                if (bl.status)
                    SetOkAndClose();
                else
                    UIMessageTip.ShowWarning(btnEditPrice, bl.msg);
            }
            catch (Exception ex)
            {
                UIMessageBox.Show("获取卡类型失败:。" + ex.Message);
            }
            finally { cmd.HideOpaqueLayer(); }
        }

        private void frmDiscounts_Shown(object sender, EventArgs e)
        {
            txtValue.Focus();
        }
    }
}
